import { useActiveObject } from '@renderer/stores/activeObject'
import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import { watch, nextTick } from 'vue'
import { gsap } from 'gsap'
import { Box3, Vector3 } from 'three'

export default function () {
  const activeObjectStore = useActiveObject()
  const { activeShallowRef } = storeToRefs(activeObjectStore)

  const viewportStore = useViewportStore()
  const { orbitControls, camera } = storeToRefs(viewportStore)
  const box = new Box3()
  const center = new Vector3()
  watch(
    () => activeShallowRef.value,
    (obj) => {
      nextTick(() => {
        if (
          orbitControls.value &&
          camera.value &&
          obj &&
          !obj.name.includes('editor-point') &&
          !obj._isEditor
        ) {
          box.setFromObject(obj)
          box.getCenter(center)

          gsap.to(orbitControls.value.target, {
            duration: 0.5,
            ...center
          })
        }
      })
    }
  )
}
